//
//  NewsViewController.m
//  ios_news
//
//  Created by Han on 14-6-9.
//  Copyright (c) 2014年 ucoder. All rights reserved.
//

#import "NewsViewController.h"
#import "NewsCell.h"
#import "News.h"
#import "LoadingView.h"
#import "GalleryNews.h"
#import "NewsDetailController.h"
#import "Util.h"
#import "NewsGalleryView.h"


@implementation NewsViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor clearColor];
    
    // 夜间模式监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doThemeChanged:)name:@"themeChange" object:nil];

    
    
    
    //self.navigationController.navigationBarHidden = YES;
    
    //self.view.backgroundColor = [UIColor redColor];
    
    // 初始数据
    mData = [NSMutableArray arrayWithCapacity:[NEWS_EN_ARRAY count]];
    for (int i = 0; i < [NEWS_EN_ARRAY count]; i++) {
        [mData addObject: [NSMutableArray arrayWithCapacity:20]];
    }
    
    mDataPage = [NSMutableArray arrayWithCapacity:[NEWS_EN_ARRAY count]];
    for (int i = 0; i < [NEWS_EN_ARRAY count]; i++) {
        [mDataPage addObject: [NSNumber numberWithInteger:0]];
    }
    
    mCurrentDataPage = 0;
    
    
    mCurrentPage = 0;

    mNavScrollView = [[NavScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 64)];
    mNavScrollView.delegateNews = self;
    [self.view addSubview:mNavScrollView];
    
    mTableViewHeight = GLOBLE_HEIGHT - 64 - 49; // nav 64 tabar 49
    
    
    mNewsScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, 320, mTableViewHeight)];
    mNewsScrollView.delegate = self;
    mNewsScrollView.pagingEnabled = YES;  //控制控件是否整页翻动
    
    //newsScrollView.backgroundColor = [UIColor darkGrayColor];
    
    for (int i = 0; i < [NEWS_EN_ARRAY count]; i++) {
        NewsTableView *tableView = [[NewsTableView alloc] initWithFrame:CGRectMake(320 * i, 0, 320, mTableViewHeight)];
        
        if (i == 0) {
            mCurrentTableView = tableView;
        }
        
        if ([[NEWS_EN_ARRAY objectAtIndex:i] isEqualToString:@"news_global"]) {
            [self addGallery:tableView];
        }
        
        
        [tableView setTag:i + [NewsTableView getViewTag]];
        
        tableView.delegate = self;
        tableView.dataSource = self;
        //tableView.hidden = YES;
        
        
        // 等待view
        //[LoadingView add:self.view initWithFrame:CGRectMake(320 * i, 44, 320, mTableViewHeight) viewTag:([LoadingView getViewTag] + i)];
        [LoadingView add:tableView viewTag:([LoadingView getViewTag] + i)];

        
        
        
        // 刷新头
        EGORefreshTableHeaderView *refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - tableView.bounds.size.height, tableView.frame.size.width, tableView.bounds.size.height)];
        
        [refreshHeaderView setTag:i + [EGORefreshTableHeaderView getViewTag]];
        
        refreshHeaderView.delegate = self;
        
        if (i == 0) {
            mCurrentRefreshHeaderView = refreshHeaderView;
        }
        
        [tableView addSubview:refreshHeaderView];
    

        // 底部加载更多view
        tableView.tableFooterView = nil;
        LoadMoreView *loadMoreView = [[LoadMoreView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, tableView.bounds.size.width, 40.0f)];
        [loadMoreView setTag:i + [LoadMoreView getViewTag]];
        
        if (i == 0) {
            mCurrentLoadMoreView = loadMoreView;
        }
        
        tableView.tableFooterView = loadMoreView;
        tableView.tableFooterView.hidden = YES;
        
         
        [mNewsScrollView addSubview:tableView];
        
    }
    
    
    mNewsScrollView.contentSize = CGSizeMake(320 * [NEWS_EN_ARRAY count], mTableViewHeight);
    
    [self.view addSubview:mNewsScrollView];
    
    [self fristLoadData];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    //NSLog(@"1111111111111");
    
    mCurrentData = [NSMutableArray arrayWithArray:[self getFav:[NSArray arrayWithArray:mCurrentData]]] ;
    
    [mCurrentTableView reloadData];
    
    [MobClick beginLogPageView:@"NewsViewController"];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"NewsViewController"];
}

- (void) loadData
{

    NSString *url = [[NSString alloc] initWithFormat:@"%@%@", [API_NEWS objectForKey:[NEWS_EN_ARRAY objectAtIndex:mCurrentPage]], mCurrentDataPage];
    
    mReloading = YES;
    
    NSURLSessionTask *task = [News getDataWithBlock:^(NSArray *data, NSError *error) {
        if (!error) {
            
            [mCurrentRefreshHeaderView refreshLastUpdatedDate];
            
            mReloading = NO;
            //[self doneLoadingTableViewData];
            
            // 查看已收藏
            data = [self getFav:data];
            
            [[mData objectAtIndex:mCurrentPage] addObjectsFromArray: data];
            mCurrentData = [mData objectAtIndex:mCurrentPage];
            //NSLog(@"%@", mData);
            
            LoadingView *loadingView = (LoadingView *) [mCurrentTableView viewWithTag:mCurrentPage + [LoadingView getViewTag]];
            [loadingView removeFromSuperview];

            
            [mCurrentTableView reloadData];
            mCurrentTableView.hidden = NO;
            mCurrentTableView.tableFooterView.hidden = NO;
            
            mCurrentDataPage = [NSNumber numberWithInteger: [mCurrentDataPage intValue] + 1];
            
        } else {
            NSLog(@"%@", error);
        }
    } :url];
    
    //NSLog(@"%@", task);
    
    /*
     if (task) {
     if (task.state != NSURLSessionTaskStateCompleted) {
     if (task.state == NSURLSessionTaskStateRunning) {
     //NSLog(@"111111");
     } else {
     //NSLog(@"222222");
     }
     
     }
     }*/


}


- (NSArray *) getFav:(NSArray *)data
{
    for (int i = 0; i < data.count; i++) {
        LibSqlite *db = [LibSqlite shareInstance];
        
        News *news = [data objectAtIndex:i];
        
        NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(*) FROM favorite_news WHERE news_id ='%ld'", news.nid];
        //NSLog(@"%@", sql);
        
        if ([db getCount:sql] > 0) {
            news.isFav = YES;
        } else {
            news.isFav = NO;
        }
    }
    
    return data;

}


- (void) fristLoadData
{
    if (mCurrentTableView.mIsFristLoad == NO) {
        return;
    }
    
    [self loadData];
    mCurrentTableView.mIsFristLoad = NO;
}


- (void) addGallery:(UITableView *)tableView
{

    
    //GalleryView *galleryView = [[GalleryView alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
    //galleryView.backgroundColor = [UIColor greenColor];
    
    
    UIImageView *galleryView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 180)];
    [galleryView setImage:[UIImage imageNamed:@"gallery_holder"]];
    
    tableView.tableHeaderView = nil;
    tableView.tableHeaderView = galleryView;
    

    NSString *url = [[NSString alloc] initWithFormat:@"%@", API_GALLERY];
    
    [GalleryNews getDataWithBlock:^(NSArray *data, NSError *error) {
        
        if (!error) {
            
            //NSLog(@"%@", data);
            
            NewsGalleryView *galleryView = [[NewsGalleryView alloc] initWithFrame:CGRectMake(0, 0, 320, 180) :data :self.navigationController];
            
            
            tableView.tableHeaderView = nil;
            tableView.tableHeaderView = galleryView;
            
        } else {
            NSLog(@"%@", error);
        }
        
    } :url];
    
    
    tableView.tableHeaderView = nil;
    tableView.tableHeaderView = galleryView;
    
    
}


- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //NSMutableArray *currentData = [mData objectAtIndex:mCurrentPage];
    
    //NSLog(@"currentData count = %i", [currentData count]);
    
    static NSString *CellIdentifier = @"NewsListCell";
    NewsCell *cell = (NewsCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[NewsCell alloc] initWithStyle:UITableViewCellStyleDefault
                               reuseIdentifier:CellIdentifier];
    }

    cell.news = [mCurrentData objectAtIndex:(NSUInteger)indexPath.row];
    
    return cell;
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [mCurrentData count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

// cell点击处理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; // 选中后立刻转为未选中
    
    //NewsDetailController *newsDetailCtr = [[NewsDetailController alloc] init];
    
    News *news = [mCurrentData objectAtIndex:(NSUInteger)indexPath.row];
    //UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    NewsDetailController *newsDetailCtr = [[NewsDetailController alloc] initWithNibName:nil bundle:nil nid:news.nid];
    newsDetailCtr.hidesBottomBarWhenPushed = YES; // 详情页隐藏tabbar
    
    /*
    CATransition *animation = [CATransition animation];
    animation.duration = 0.5;
    //animation.timingFunction = UIViewAnimationCurveEaseInOut;
    //animation.type = @"oglFlip";
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromRight;
    [self.view.window.layer addAnimation:animation forKey:nil];
    [newsDetailCtr setModalTransitionStyle:UIModalTransitionStylePartialCurl];
     
     */
    
    //UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] init];
    //backBarButtonItem.title = @"返回";
    //self.navigationItem.backBarButtonItem = backBarButtonItem;
    
    self.navigationController.navigationBar.barTintColor = MAIN_COLOR;
    
    [self.navigationController pushViewController:newsDetailCtr animated:YES];
    //[self.navigationController pushViewController:newsDetailCtr animated:YES];
    
}


#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
	[self reloadTableViewDataSource];
    
	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:2.0];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    
	return mReloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
	
	return [NSDate date]; // should return date data source was last changed
	
}


- (void)reloadTableViewDataSource
{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	
    
    [[mData objectAtIndex:mCurrentPage] removeAllObjects];
	mCurrentDataPage = 0;
    
    [self loadData];
}

- (void)doneLoadingTableViewData
{
	
    
	//  model should call this when its done loading
	mReloading = NO;
    
	[mCurrentRefreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:mCurrentTableView];
	
}



- (void) newsScrollViewSetContentOffset:(int)currentPage
{
    mCurrentPage = (NSInteger) currentPage;
    
    [self setCurrentElement];
    
    [mNewsScrollView setContentOffset:CGPointMake(320 * currentPage, 0) animated:NO];
}


// 滚动就触发
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    
    if ([scrollView isKindOfClass:[NewsTableView class]]) {
            
        [mCurrentRefreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
        
        return;
    }

    
    [mNavScrollView changeIndicatorViewContentOffset: scrollView.contentOffset.x / 320];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    
    if ([scrollView isKindOfClass:[UITableView class]]) {
        [mCurrentRefreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
        return;
    }
}


// 减速停止了时执行
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    //NSLog(@"scrollViewDidEndDecelerating");
    
    if ([scrollView isKindOfClass:[NewsTableView class]]) {
        
        /*
        //tableview 滑动到底部的时候 开始加载更多
        CGPoint contentOffsetPoint = scrollView.contentOffset;
        CGRect frame = scrollView.frame;
        if (contentOffsetPoint.y >= scrollView.contentSize.height - frame.size.height || scrollView.contentSize.height < frame.size.height)
        {
            NSLog(@"+++++");
            //if (!_requestState.isPullUpRequest) {
               // [self doPullUpRequest];
            //}
        }
        */
        
        // 下拉到最底部时显示更多数据
        if(scrollView.contentOffset.y >= ((scrollView.contentSize.height - scrollView.frame.size.height))) {
            
            //NSLog(@"+++++");
            [self loadData];
        }
        
        
        
        return;
    }
    
    
    mCurrentPage = (NSInteger) (scrollView.contentOffset.x/320);
    [self setCurrentElement];
    
    
    [self fristLoadData];
    
    [mNavScrollView adjustNavScrollView: mCurrentPage + 100];
    
    //NSLog(@"mCurrentPage=%li", (long)mCurrentPage);
    
}

- (void) setCurrentElement {
    mCurrentData = [mData objectAtIndex:mCurrentPage];
    mCurrentTableView = (NewsTableView *) [self.view viewWithTag:mCurrentPage + [NewsTableView getViewTag]];
    mCurrentRefreshHeaderView = (EGORefreshTableHeaderView *) [self.view viewWithTag:mCurrentPage + [EGORefreshTableHeaderView getViewTag]];
    mCurrentLoadMoreView = (LoadMoreView *) [self.view viewWithTag:mCurrentPage + [LoadMoreView getViewTag]];
    
    mCurrentDataPage = [mDataPage objectAtIndex:mCurrentPage];
}


- (void)doThemeChanged:(NSNotification*) notification
{
    if ([notification.name isEqualToString:@"themeChange"]) {
        NSLog(@"NewsViewController - themeChange");
        if ([Util isNightMode]) {
            self.view.backgroundColor = ColorWithRGB(34, 34, 34);
        } else {
            self.view.backgroundColor = ColorWithRGB(236, 236, 236);
        }
        
    }
}


@end
